<template>
  <div class="lucky-draw">
    <div class="lucky-draw-content">
      <iframe id="newdexGame_iframe" name="newdexGame_iframe" frameborder="0" style="height: 100%; width: 100%;transition: opacity .3s ease-in-out;"
        :src="`${luckUrl}/luck-draw?source=web&language=${language}&v=${vesen}`"></iframe>
        <div v-loading="luckyDrawLoading" class="luckyDrawLoading"></div>
    </div>
    <!-- 用户登录 钱包选择 -->
    <el-dialog
      class="walletLoginDiaog"
      :close-on-click-modal="false"
      :visible.sync="walletLoginVisible"
      width="980px">
      <wallet-login @listenWalletLoginClose="walletLoginVisible = false" :walletLoginShow="walletLoginVisible"/>
    </el-dialog>

    <!-- 钱包授权 -->
    <el-dialog
      class="walletTitle"
      :title="$t('wallet.promistLogin')"
      :show-close= 'true'
      :close-on-click-modal="false"
      :visible.sync="walletVisible"
      width="680px">
      <wallet-permission @listenWalletClose="walletVisible=false; walletLoginVisible=true"/>
    </el-dialog>
  </div>
</template>

<script>
// import { EosModel } from '@/utils/eos/index';
import { authorized, getReqUrl } from '@/utils/validate';
import WalletPermission from '@/components/WalletPermission';
import WalletLogin from '@/components/WalletLogin';

export default {
  name: 'luckyDraw', // 幸运抽奖
  data() {
    return {
      walletVisible: false, // 钱包授权
      walletLoginVisible: false, // 钱包登录系统
      luckyDrawLoading: true,
      language: 'en',
      vesen: '', // 随机码清缓存
      targetOrigin: `https://m.${window.location.host}`, // 与dapp 通讯地址
      luckUrl: '',
    }
  },
  components: {
    WalletPermission,
    WalletLogin,
  },
  props: {},
  watch: {
    '$store.state.app.language': function change(val) {
      this.language = val;
    },
    '$store.state.app.scatter.identity': {
      handler: function listen() {
        const app = this.$store.state.app;
        const response = {
          account: app.scatter.identity ? app.scatter.identity.accounts[0].name : null,
          token: localStorage.getItem('Frontend-Token'),
          level: app.accountInfo ? app.accountInfo.level : 0,
          chain: app.scatter.chain,
        };
        this.responseMessage('getAccount', response);
      },
      deep: true,
    },
  },
  computed: {},
  created() {
    this.luckUrl = this.targetOrigin;
    document.title = this.$t(`rout.${this.$route.meta.title}`);
  },
  mounted() {
    const env = process.env.NODE_ENV;
    this.language = this.$store.state.app.language;
    switch (env) {
      case 'development':
        this.luckUrl = `http://${getReqUrl('ip')}:${process.env.VUE_APP_PORT14}`
        this.targetOrigin = this.luckUrl;
        break;
      default:
        this.targetOrigin = `https://m.${window.location.host}`;
        this.luckUrl = this.targetOrigin;
        break;
    }
    this.vesen = new Date().getTime();
    // 抽奖 与 dapp 互通
    this.postMessageForDapp();
  },
  beforeDestroy() {
    this.handleDrawWindow();
  },
  methods: {
    // 中断与dapp互通
    handleDrawWindow() {
      window.removeEventListener('message', this.listenerLuckyDraw, false);
    },

    // 抽奖 与 dapp 互通
    postMessageForDapp() {
      window.addEventListener('message', this.listenerLuckyDraw, false);
    },

    listenerLuckyDraw(event) {
      const app = this.$store.state.app;
      const origin = event.origin || event.originalEvent.origin;
      if (origin !== this.targetOrigin) return;
      const message = event.data;
      // 发送用户给dapp
      if (message.action === 'getAccount') {
        const response = {
          account: app.scatter.identity ? app.scatter.identity.accounts[0].name : null,
          token: localStorage.getItem('Frontend-Token'),
          level: app.accountInfo ? app.accountInfo.level : 0,
          chain: app.scatter.chain,
        };
        this.responseMessage(message.action, response);
      }

      // 用户登录、授权
      if (message.action === 'accountAction') {
        const data = message.data;
        if (!data.account) {
          // 未登录 -- 发起登录
          this.handleWalletPermission();
          return;
        }
        if (!data.token) {
          // 未授权 -- 发起授权
          this.handleAuthorized(() => {
            const response = {
              account: app.scatter.identity ? app.scatter.identity.accounts[0].name : null,
              token: localStorage.getItem('Frontend-Token'),
              level: app.accountInfo ? app.accountInfo.level : 0,
              authorized: true,
              chain: app.scatter.chain,
            };
            this.responseMessage('getAccount', response);
          })
          return;
        }
      }

      // 开通会员 、升级会员
      if (message.action === 'toMemberAction') {
        this.luckyDrawVisible = false;
        this.$router.push('/member');
      }
    },

    // response for dapp
    responseMessage(action, data) {
      const iframe = document.getElementById('newdexGame_iframe');
      if (iframe) {
        const message = { action, data }
        iframe.contentWindow.postMessage(message, this.targetOrigin);
      }
    },

    // 登录授权
    handleWalletPermission() {
      const checkWallet = localStorage.getItem('checkWallet');
      if (!Number(checkWallet)) {
        this.$emit('listenWalletPermission', true); // 授权
        return;
      }
      this.walletLoginVisible = true; // 登录显示
    },

    // 授权操作
    handleAuthorized(callback) {
      authorized(this, (code, result) => {
        if (code === 'error') { // 授权错误
          console.log(result); // eslint-disable-line
          return;
        }
        callback();
      });
    },
  },
}
</script>
<style lang="scss" scoped>
.lucky-draw {
  // 活动抽奖弹窗

  .lucky-draw-content {
    width: 750px;
    margin: 2vh auto;
    position: relative;
    height: 1250px;

    .luckyDrawLoading {
      position: absolute;
      top: 48%;
      left: 0;
      right: 0;
      margin: auto;
      z-index: 8;
      transform: scale(1.8);
    }

    #newdexGame_iframe {
      position: relative;
      z-index: 9;
    }
  }
}

.walletLoginDiaog /deep/.el-dialog__body{
  padding-top: 10px;
  padding-bottom: 40px;
}
</style>

